<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">

      <!--<el-input v-model="listQuery.date" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="请输入发货日期"/>-->
      <el-date-picker
        v-model="listQuery.startToEnd"
        :picker-options="pickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator=" 至 "
        start-placeholder="开始日期"
        end-placeholder="结束日期"/>
      <!-- <el-input v-model="listQuery.batchNumber" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="产品批号"/>-->
      <el-select v-model="listQuery.batchNumber" clearable placeholder="请选择产品批号">
        <el-option
          v-for="(value, key) in batchNumbers"
          :key="key"
          :label="value"
          :value="key"/>
        <!--<el-option
          v-for="item in batchNumbers"
          :key="item.value"
          :label="item.label"
          :value="item.label">
        </el-option>-->
      </el-select>
      <!--  <el-input v-model="listQuery.userDepartments" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入使用部门"/>-->
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="selectedOrderInfo">查看选中的订单</el-button>
      <el-button
        :loading="downloadLoading"
        size="mini"
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        @click="handleDownload">导出
      </el-button>
      <!--      <el-input type="file" v-model="data.formData" size="mini" class="filter-item" style="width: 200px;"-->
      <!--                placeholder="请选择文件"/>-->
      <!--      <el-button :loading="downloadLoading" v-model="data.formData" size="mini" class="filter-item" type="warning"-->
      <!--                 icon="el-icon-download" @click="uploadExcel">上传订单-->
      <!--      </el-button>-->
      <!-- <el-upload class="upload-demo" action="http://192.168.1.4:8082/demo/admin/iorder/uploadExcels" :on-:limit="1" :file-list="fileList"
                 accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, .xlsx">
        <el-button type="primary">
          选择文件
          <i class="el-icon-upload el-icon&#45;&#45;right"></i>
        </el-button>
      </el-upload>-->
      <!--<el-table v-if="list.length" :data="list" style="width: 100%">
        <el-table-column prop="num" label="序号" width="100" />
        <el-table-column prop="names" label="名称" width="200" />
        <el-table-column prop="links" label="链接" width="200" />
        <el-table-column prop="passwords" label="密码" />
      </el-table>
      <el-pagination class="page" v-if="list.length" layout="prev, pager, next" :total="20" />-->
      <!--<el-upload
        style="display: inline"
        :show-file-list="false"
        :on-success="onSuccess"
        :on-error="onError"
        :before-upload="beforeUpload"
        action="/demo/admin/iorder/insertMany">
        <el-button size="mini" type="success"  :icon="uploadBtnIcon">导入</el-button>
      </el-upload>-->
      <!--<input type="file" ref="myfile">-->
      <!--<el-button @click="importData" type="success" size="mini" icon="el-icon-upload2">导入数据</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column align="center" min-width="40" label="选中" prop="isSelected" type="selection">
        <!--<template slot-scope="scope" >
          <el-checkbox v-model="checked" ></el-checkbox>
        </template>-->
      </el-table-column>
      <el-table-column type="expand" label="包材信息">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="C铅罐">
              <span>{{ props.row.leadC }}</span>
            </el-form-item>
            <el-form-item label="A型桶">
              <span>{{ props.row.drumA }}</span>
            </el-form-item>
            <el-form-item label="C型桶">
              <span>{{ props.row.drumC }}</span>
            </el-form-item>
            <el-form-item label="B型桶">
              <span>{{ props.row.drumB }}</span>
            </el-form-item>
            <el-form-item label="B型铅罐">
              <span>{{ props.row.leadB }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="70" label="序号" prop="id" sortable/>

      <el-table-column align="center" min-width="90" label="发货日期" prop="date"/>
      <el-table-column align="center" min-width="90" label="产品批号" prop="batchNumber"/>
      <el-table-column align="center" min-width="60" label="件数" prop="pieces"/>
      <el-table-column align="center" min-width="100" label="订货量空运(Ci)" prop="orderCount1"/>
      <el-table-column align="center" min-width="100" label="订货量铁运(Ci)" prop="orderCount2"/>
      <el-table-column align="center" min-width="100" label="订货量汽运(Ci)" prop="orderCount3"/>
      <!--<el-table-column align="center" min-width="200" label="检定单位" prop="verfier" />-->
      <!--<el-table-column align="center" min-width="200" label="证书编号" prop="vertificateNo" />-->
      <el-table-column align="center" min-width="80" label="分装总体积(ml)" prop="splitVolume"/>
      <el-table-column align="center" min-width="80" label="分装总活度(Ci)" prop="splitActivity"/>
      <!--<el-table-column align="center" min-width="200" label="是否有效" prop="isEffective" />-->
      <el-table-column align="center" min-width="80" label="浓度" prop="concentration" sortable/>
      <el-table-column align="center" min-width="100" label="测量时间" prop="measureTime"/>
      <el-table-column align="center" min-width="80" label="生产量(Ci)" prop="productionActivity"/>
      <el-table-column align="center" min-width="80" label="生产量(ml)" prop="productionQuantity"/>
      <el-table-column align="center" min-width="80" label="剩余量(Ci)" prop="remainActivity"/>
      <el-table-column align="center" min-width="80" label="剩余量(ml)" prop="remainVolume"/>
      <!--<el-table-column align="center" min-width="200" label="邻碘马尿酸钠" prop="sodiumHippurate" />-->
      <el-table-column align="center" min-width="90" label="备注" prop="notes"/>
      <!--<el-table-column align="center" label="详细信息" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">查看</el-button>
        </template>
      </el-table-column>-->
      <!--<el-table-column align="center" min-width="100px" label="文档类型" prop="iorderType">
        <template slot-scope="scope">{{ scope.row.iorderType | formatiorderType }}</template>
      </el-table-column>
      <el-table-column align="center" label="是否有效" prop="isEffective">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isEffective ? 'success' : 'error' ">{{ scope.row.isEffective ? '无效' : '有效' }}</el-tag>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate2(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"/>

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100"/>
    </el-tooltip>

  </div>
</template>

<style>
  .el-dialog {
    width: 60%;
  }

  .table-expand {
    font-size: 0;
  }

  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }

  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }

  .gallery {
    width: 80px;
    margin-right: 10px;
  }
</style>

<script>

import { listiorders, listiorders2, deleteiorders, insertAlliorder, uploadExcels, downloadExcels, showDateOrders } from '@/api/business/iorder'
import BackToTop from '@/components/BackToTop'
import {
  listBachNumbers2,
  detailproductInfo,
  detailCF,
  createOrderList,
  createStock,
  catchTotalInfo,
  createShipAccord,
  getOAsheet,
  getSplitSheet,
  getSplitSheet2
} from '@/api/business/productProduction'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import axios from 'axios'

export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: '/iorder/insertMany',
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
export default {
  name: 'IorderList',
  components: { BackToTop, Pagination },
  filters: {
    formatiorderType(iorderType) {
      if (iorderType === 1) {
        return '操作规程'
      } else if (iorderType === 2) {
        return '管理器材'
      } else {
        return '规章制度'
      }
    },
    formatPerson(personId) {
      if (personId === 0) {
        return '正常'
      } else if (personId === 1) {
        return '已过期'
      } else {
        return '已下架'
      }
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      batchNumbers: [],
      loading: false,
      date: new Date(),
      multipleSelection: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      value1: '',
      value2: '',
      files: [],
      dates: [],
      newAttachmentsTable: [],
      insert: true,
      noPersonalInformation: [],
      listQuery: {
        page: 1,
        limit: 20,
        iorders: {},
        customerName: '',
        batchNumber: '',
        startToEnd: [],
        sort:'date',
        order:'desc'
      },
      iorderDetail: '',
      detailDialogVisible: false,
      downloadLoading: false,
      btnText: '',
      formData: []
    }
  },
  created() {
    this.getBatchNumbers()
  },
  mounted() {
    this.getList()
    /*    this.fetchCascaderData()*/
  },
  methods: {
    importData() {
      const myfile = this.$refs.myfile
      const files = myfile.files
      const file = files[0]
      var formData = new FormData()
      formData.append('file', file)
      this.uploadFileRequest('/admin/demo/iorder/insertMany', formData).then(resp => {
        if (resp) {
          console.log(resp)
        }
      })
    },
    getList() {
      this.listLoading = true
      listiorders2(this.listQuery).then(response => {
        this.list = response.data.data.items
        console.log(response.data.data.items)
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    onSuccess(response, file, fileList) {
      this.enabledUploadBtn = true
      this.files = fileList
      this.uploadBtnIcon = 'el-icon-upload2'
      this.btnText = '数据导入'
      insertAlliorder(data).then(response => {
        this.$notify.success({
          title: '成功',
          message: '创建成功'
        })
        this.$router.push({ path: '/iorder/list' })
      }).catch(response => {
        MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
          confirmButtonText: '确定',
          type: 'error'
        })
      })
    },
    getBatchNumbers() {
      listBachNumbers2(this.listQuery).then(response => {
        this.batchNumbers = response.data.data.batchNumbers/* .sort((a, b) => new Date(a) - new Date(b))*/
        /*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*/
      }).catch(() => {
        console.log('getList catch')
        /* this.listStockss = []
          /!*this.total1 = 0*!/
          this.listLoading = false*/
      })
    },
    /* getBatchNumbers() {
        listBachNumbers(this.query).then(response => {
          this.batchNumbers = response.data.data.batchNumbers/!*.sort((a, b) => new Date(a) - new Date(b))*!/
          /!*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*!/
        }).catch(() => {
          console.log('getList catch')
          /!*this.listStockss = []
          /!*this.total1 = 0*!/
          this.listLoading = false*!/
        })

      },*/
    uploadExcel(event) {
      /* const files=event.target.file;*/
      /* let formData=new FormData()
         formData.append(files,element.file);*/
      /* this.listLoading = true*/
      /* this.listQuery.file[0]= null*//* event.target.file;*/
      /* let myfile = this.$refs.myfile;
         let files = myfile.files;
         let file = files[0];*/
      const formData = new FormData()

      formData.append('file', this.files[0])
      axios({
        method: 'post',
        url: 'http://localhost:8082/demo/admin/iorder/uploadExcels',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(function(response) {
        console.log(response)
        alert('文件上传成功！')
      }).catch(function(error) {
        console.log(error)
        alert('文件上传失败！')
      })

      // this.listQuery.formData=formData
      // uploadExcels(formData).then(response => {
      //   this.list = response.data.data.items
      //   this.total = response.data.data.total
      //   this.listLoading = false
      // }).catch(() => {
      //   this.list = []
      //   this.total = 0
      //   this.listLoading = false
      // })
    },
    selectedOrderInfo() {
      this.multipleSelection.map(function(element) {
        if (!this.dates.includes(element.date)) {
          this.dates.push(element.dates)
        }
      })
      console.log(this.dates)
      showDateOrders(this.dates).then(response => {

      })
    },
    handleSelectionChange(val2) {
      this.multipleSelection = val2
    },

    beforeUpload(file) {
      this.enabledUploadBtn = false
      this.uploadBtnIcon = 'el-icon-loading'
      this.btnText = '正在导入'
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/iorders/create' })
    },
    handleUpdate2(row) {
      this.$router.push({ path: '/iorder/edit', query: { id: row.id }})
    },
    handleUpdate(row) {
      this.$router.push({ path: '/iorder/edit', query: { id: row.id }})
    },
    showDetail(detail) {
      this.iorderDetail = detail
      this.detailDialogVisible = true
    },

    handleDelete(row) {
      deleteiorders(row).then(response => {
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true

        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '发货日期', '件数', '包装材料ID', '空运订量', '铁运订量', '汽运订量', '产品批号', '分装量', '活度', '测量时间', '生产量', '剩余量', '邻碘马尿酸钠', '备注']
          const filterVal = ['id', 'date', 'pieces', 'packageId', 'orderCount1', 'orderCount2', 'orderCount3', 'batchNumber', 'splitCount', 'activity', 'mearsureTime', 'remarks', 'iorderStatus', 'overdue']
          excel.export_json_to_excel2(tHeader, this.list, filterVal, '碘131化钠口服溶液订单信息表')
          this.downloadLoading = false
        })
    }
  }
}
</script>
